package com.bsj.travel.config.mybatis;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.bsj.crypt.config.QueryInterceptor;
import com.bsj.crypt.config.UpdateInterceptor;
import com.bsj.crypt.crypt.aes.AESUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;
import java.util.List;

/***
 * @description MybatisEncryptConfiguration
 * @author LiJiaXin
 * @version 1.0.0
 * @time 2024/1/10 13:57
 **/
@Configuration
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MybatisEncryptConfiguration {

    /**
     * 16位随机AES密钥
     */
    @Value("${mybatis.secret}")
    private String secret;

    /**
     * 数据源
     */
    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    /**
     * 初始化加密工具类
     */
    @PostConstruct
    public void init() {
        if (StringUtils.isNotEmpty(secret)) {
            AESUtils.setSecret(secret);
        }
        try {
            AESUtils.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加拦截器
     */
    @PostConstruct
    public void addPageInterceptor() {
        QueryInterceptor queryInterceptor = new QueryInterceptor();
        UpdateInterceptor updateInterceptor = new UpdateInterceptor();
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            sqlSessionFactory.getConfiguration().addInterceptor(queryInterceptor);
            sqlSessionFactory.getConfiguration().addInterceptor(updateInterceptor);
        }
    }

}
